package com.sl.ms.trade.handler.alipay;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.alipay.easysdk.kernel.Config;
import com.sl.ms.trade.constant.PayChannelCacheConstant;
import com.sl.ms.trade.constant.TradingConstant;
import com.sl.ms.trade.entity.PayChannelEntity;
import com.sl.ms.trade.enums.TradingEnum;
import com.sl.ms.trade.service.PayChannelService;
import com.sl.transport.common.exception.SLException;
import com.sl.transport.common.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author wjh
 * @create 2023-09-22 15:16
 */
@Component
public class AlipayConfig {

    private static StringRedisTemplate stringRedisTemplate;

    @Autowired
    public AlipayConfig(StringRedisTemplate stringRedisTemplate) {
        AlipayConfig.stringRedisTemplate = stringRedisTemplate;
    }
    /**
     * 将支付渠道配置转化为支付宝的配置
     *
     * @param enterpriseId 商户ID
     * @return 支付宝的配置
     */
    public static Config getConfig(Long enterpriseId) {
        String key = PayChannelCacheConstant.PAY_CHANNEL_CONFIG_CACHE;

        Object configJson = stringRedisTemplate.opsForHash().get(key, PayChannelCacheConstant.HASH_KEY_ALI_PAY + enterpriseId);
        if (cn.hutool.core.util.ObjectUtil.isNotEmpty(configJson)) {
            Config config = JSONUtil.toBean((String) configJson, Config.class);
            return config;
        }
        PayChannelService payChannelService = SpringUtil.getBean(PayChannelService.class);
        PayChannelEntity ali_pay = payChannelService.findByEnterpriseId(enterpriseId, TradingConstant.TRADING_CHANNEL_ALI_PAY);
        if (ObjectUtil.isEmpty(ali_pay)) {
            throw new SLException(TradingEnum.CONFIG_EMPTY);
        }

        Config config = new Config();
        config.protocol = "https";
        config.gatewayHost = ali_pay.getDomain();
        config.signType = "RSA2";
        config.appId = ali_pay.getAppId();
        config.merchantPrivateKey = ali_pay.getMerchantPrivateKey();
        config.alipayPublicKey = ali_pay.getPublicKey();
        config.notifyUrl = ali_pay.getNotifyUrl();
        config.encryptKey = ali_pay.getEncryptKey();
        //存入redis
        stringRedisTemplate.opsForHash().put(key, PayChannelCacheConstant.HASH_KEY_ALI_PAY+enterpriseId, JSONUtil.toJsonStr(config));
        return config;

    } 
}
